<?php
/**
 * 订单处理服务类
 * Enter description here ...
 * @author Administrator
 *
 */
class CouponsService {
	protected $shxx = array (); //获取收货信息
	protected $user = array ();
	//以下三个参数对应的是积分记录 而不是订单
	private $_chargeType = array ("充值" => 0, "消费" => 1, "赠送" => 2 );
	private $_payment = array ("收入" => 0, "支出" => 1 );
	private $_status = array ("全部" => "0", "等待审核" => 1, "成功" => 8, "关闭" => - 1 );
	private $_num = 20;
	
	/**
	 * 产品类型 由系统检查而不是用户提交
	 * @var unknown_type
	 */
	private $_goodstype = array ("coupons", "money" );
	public function audit() {
		//统计用户总账
		$userCoupons = MemberModel::instance ()->getSumCouponsMember ();
		//获取期初余额
		$audit = CouponsModel::instance ()->getLastAudit ();
		//获取所有支出 根据结算的sno号 已经确认
		$audit ['coupon_no'] = $audit ['coupon_no'] > 0 ? $audit ['coupon_no'] : 0;
		$spend = CouponsModel::instance ()->getLastSpend ( $audit ['coupon_no'], 8 );
		//所有支出  等待审核
		$unconfirmed = CouponsModel::instance ()->getLastSpend ( $audit ['coupon_no'], 1 );
		$spendTotal = $spend ['spend'] + $unconfirmed ['spend'];
		//获取所有收入 根据结算的流水号
		$income = CouponsModel::instance ()->getLastIncome ( $audit ['coupon_no'] );
		$shengyu = ($audit ['balance'] + $audit ['unconfirmed'] + $spendTotal + $income ['income']);
		$status = round ( $shengyu, 2 ) == round ( $userCoupons ['total'], 2 ) ? "ok" : round ( $shengyu, 2 ) - round ( $userCoupons ['total'], 2 );
		//获取最老一笔未确认的订单
		$lastCouponsId = CouponsModel::instance ()->getMinUnConfirmedId ();
		//修正当未确认为0的时候
		if ($lastCouponsId ['id'] < 1) {
			$lastCouponsId = CouponsModel::instance ()->getMaxCoupons ();
		} else {
			$lastCouponsId ['id'] = $lastCouponsId ['id'] - 1;
		}
		return array ('unconfirmed' => abs ( $unconfirmed ['spend'] ), 'status' => $status, 'balance' => $userCoupons ['total'], 'spend' => abs ( $spend ['spend'] ), 'income' => $income ['income'], 'coupon_no' => $lastCouponsId ['id'] );
	}
	
	//增加审计功能
	public function verify() {
		
		$member = new MemberService ();
		for($i = 1; $i < 5000; $i ++) {
			$user = $member->getMemberByUid ( $i );
			if (empty ( $user )) {
				continue;
			}
			
			$total = $this->getSumCouponsByUid ( $i );
			
			if (round ( $user ['coupons'], 2 ) != round ( $total ['total'], 2 )) {
				echo $user ['uid'], "no";
				exit ();
			}
		}
	
	}
	//积分明细列表
	public function listing($p, $where) {
		
		$totalNum = CouponsModel::instance ()->countCouponsHisotry ( $where );
		$page = $this->page ( $totalNum, $p, $this->_num );
		$detail = CouponsModel::instance ()->getCouponsHistoryPage ( $page ['start'], $page ['num'], $where );
		return array ('list' => $this->matchChargeTypes ( $detail ), 'page' => $page, 'totalnum' => $totalNum );
	}
	
	public function status($status, $orderno) {
		CouponsModel::instance ()->setCouponsStatus ( array ('status' => $status ), array ('orderno' => $orderno ) );
	}
	
	public function getSumCouponsByUid($uid) {
		return CouponsModel::instance ()->getSumCouponsByUid ( $uid );
	}
	/**
	 * 处理收入还是支出
	 * @param unknown_type $order
	 */
	private function matchChargeTypes($order) {
		$chargeTypes = array_flip ( $this->_chargeType );
		$couponsStatus = array_flip ( $this->_status );
		foreach ( $order as $k => $v ) {
			$order [$k] ['chargetypes'] = $chargeTypes [$v ['chargetypes']];
			$order [$k] ['status'] = $couponsStatus [$v ['status']];
		}
		return $order;
	}
	/**
	 * 新增结算 增加结算后的id
	 * @param unknown_type $params
	 */
	public function setAudit($params) {
		
		if (empty ( $_POST )) {
			return "没提交任何信息";
		}
		
		if (! $this->checkAudit ( $params ['coupon_no'] )) {
			return "未确认订单之后有已经确认的订单，不允许结算";
		} else {
			CouponsModel::instance ()->addAudit ( $params );
			return "结算成功";
		}
	
	}
	
	/**
	 * 如果未确认订单之后有已经确认的订单，不允许结算
	 * @return boolean true or false
	 */
	private function checkAudit($couponsId) {
		$rs = CouponsModel::instance ()->getCouponsById ( $couponsId );
		return empty ( $rs );
	
	}
	//收入
	public function addCoupons($uid, $username, $coupons, $remark) {
		return $this->addCouponsHistory ( $uid, $username, $coupons, $remark, $this->_payment ["收入"], $this->_chargeType ["充值"], null, $this->_status ['成功'] );
	}
	//支出
	public function reduceCoupons($uid, $username, $coupons, $orderno, $remark) {
		return $this->addCouponsHistory ( $uid, $username, $coupons, $remark, $this->_payment ["支出"], $this->_chargeType ["消费"], $orderno, $this->_status ['成功'] );
	}
	
	/**
	 * 
	 * 扣除用户积分
	 * @param unknown_type $coupons
	 * @param unknown_type $uid
	 * @param unknown_type $remark
	 */
	public function addCouponsHistory($uid, $username, $coupons, $remark, $payment, $chargetypes, $orderno, $status) {
		return CouponsModel::instance ()->saveCoupons ( $uid, $username, $coupons, $remark, $payment, $chargetypes, $orderno, $status );
	}
	
	public function import(MemberService $memberService, $remark) {
		
		$filename = $_FILES ['file'] ['tmp_name'];
		if (empty ( $filename )) {
			return '请选择要导入的CSV文件！';
		}
		
		$handle = fopen ( $filename, 'r' );
		$result = $this->input_csv ( $handle ); //解析csv 
		$len_result = count ( $result );
		if (! $len_result) {
			return '没有任何数据！';
		}
		$notMatchFile = "";
		$line = "";
		for($i = 0; $i < $len_result; $i ++) { //循环获取各字段值 
			$name = iconv ( 'GBK', 'UTF-8', $result [$i] [0] ); //中文转码 
			$coupons = $result [$i] [1];
			$user = $memberService->getMemberByWhere ( array ('real_name' => trim ( $name ), 'verify' => 1 ) );
			//如果没有找到
			$format = "%s,%s,%s";
			if (empty ( $user )) {
				$line = sprintf ( $format, $result [$i] [0], $coupons, "not found" );
				$notMatchFile = $notMatchFile . $line . "\r\n";
				continue;
			}
			$row = $this->addCouponsHistory ( $user ['uid'], $user ['real_name'], $coupons, $remark, $this->_payment ["收入"], $this->_chargeType ["充值"], null, $this->_status ['成功'] );
			
			//存储没有导入的数据
			if ($row < 1) {
				$line = sprintf ( $format, $result [$i] [0], $coupons, "not write" );
				$notMatchFile = $notMatchFile . $line . "\r\n";
				continue;
			} else {
				
				$memberService->saveCoupons ( $user ['uid'], $coupons, 0 );
				$addCoupons = null;
				$coupons = 0;
			}
		}
		$data_values = substr ( $data_values, 0, - 1 ); //去掉最后一个逗号 
		fclose ( $handle ); //关闭指针 
		$this->createCSV ( $notMatchFile );
		return;
	}
	
	/**
	 * 获取统计帐
	 * Enter description here ...
	 */
	public function getAudit($limit = 20) {
		return CouponsModel::instance ()->getAudit ( $limit );
	}
	
	public function createCSV($content) {
		header ( "Cache-Control: public" );
		header ( "Pragma: public" );
		header ( "Content-type:application/vnd.ms-excel" );
		$file = date ( "md", time () );
		header ( "Content-Disposition:attachment;filename=$file.csv" );
		echo $content;
	}
	
	public function export($start, $end, $where) {
		$starttime = strtotime ( str_replace ( ".", "-", $start ) );
		$endtime = strtotime ( str_replace ( ".", "-", $end . " 23:59:59" ) );
		$shijianduan = $start . "-" . $end . " 23:59:59";
		//统计期初
		$beforeIncome = CouponsModel::instance ()->getIncomeByBeforeTime ( $starttime, $where );
		$beforeSpend = CouponsModel::instance ()->getSpendByBeforeTime ( $starttime, $where );
		$income = CouponsModel::instance ()->getIncomeByTime ( $starttime, $endtime, $where );
		$spend = CouponsModel::instance ()->getSpendByTime ( $starttime, $endtime, $where );
		$detail = CouponsModel::instance ()->getCouponsHistoryAll ( $starttime, $endtime, $where );
		$downloadtime = date ( "Y-m-d H:i:s", time () );
		$baseinfo = "\r\n时间段,%s\r\n期初,%s\r\n订单数,%s\r\n积分收入,%s\r\n积分支出,%s\r\n积分余额,%s\r\n下载时间,%s";
		$couponsBalance = $beforeIncome ['income'] + $beforeSpend ['spend'] + $income ['income'] + $spend ['spend'];
		echo sprintf ( $baseinfo, $shijianduan, $beforeIncome ['income'] + $beforeSpend ['spend'], count ( $detail ), $income ['income'], $spend ['spend'], $couponsBalance, $downloadtime );
		echo "\r\n";
		echo $title = "流水号,充值时间,渠道,名称,收款人,收入,支出,收支,状态";
		echo "\r\n";
		$foramt = "%s,%s,%s,%s,%s,%s,%s,%s,%s";
		$payment = array_flip ( $this->_payment );
		$chargeType = array_flip ( $this->_chargeType );
		$status = array_flip ( $this->_status );
		foreach ( $detail as $v ) {
			if ($v ['payment'] == 1) {
				echo sprintf ( $foramt, $v ['id'], date ( "Y-m-d H:i:s", $v ['date'] ), $chargeType [$v ['chargetypes']], $v ['remark'], $v ['username'], "", $v ['coupons'], $payment [$v ['payment']], $status [$v ['status']] );
			} else {
				echo sprintf ( $foramt, $v ['id'], date ( "Y-m-d H:i:s", $v ['date'] ), $chargeType [$v ['chargetypes']], $v ['remark'], $v ['username'], $v ['coupons'], "", $payment [$v ['payment']], $status [$v ['status']] );
			}
			echo "\r\n";
		}
	}
	
	public function setCsvHeader() {
		header ( "Cache-Control: public" );
		header ( "Pragma: public" );
		header ( "Content-type:application/vnd.ms-excel" );
		$file = date ( "md", time () );
		header ( "Content-Disposition:attachment;filename=$file.csv" );
	}
	private function input_csv($handle) {
		$out = array ();
		$n = 0;
		while ( $data = fgetcsv ( $handle, 10000 ) ) {
			$num = count ( $data );
			for($i = 0; $i < $num; $i ++) {
				$out [$n] [$i] = $data [$i];
			}
			$n ++;
		}
		return $out;
	}
	
	/**
	 * 分页
	 *
	 * @return Array
	 */
	private function page($total, $pageid, $num) {
		$pageid = isset ( $pageid ) ? $pageid : 1;
		$start = ($pageid - 1) * $num;
		$pagenum = ceil ( $total / $num );
		/*修正分类不包含内容 显示404错误*/
		$pagenum = $pagenum == 0 ? 1 : $pagenum;
		/*如果超过了分类页数 404错误*/
		
		if ($pageid > $pagenum) {
			return false;
		}
		
		$page = array ('start' => $start, 'num' => $num, 'current' => $pageid, 'page' => $pagenum );
		return $page;
	}

}